const FriendShip = require('../model/Friend_model')
const { getUserInfo } = require('./UserService')
const { Op, where } = require('sequelize')
class FriendService {
    // 查询是否为好友关系
    async isFriend(userId, friendId) {
        const res = await FriendShip.findAll({
            attributes: ['userId', 'friendId', 'status'],
            where: {
                [Op.or]: [{ userId, friendId }, { userId: friendId, friendId: userId }]
            }
        })
        if (res)
            return res
    }

    //单向查询1
    async wildFriend(userId, friendId) {
        const res = await FriendShip.findAll({
            attributes: ['userId', 'friendId', 'status'],
            where: {
                [Op.or]: [{ userId, friendId }]
            }
        })
        return res
    }

    //单向查询2
    async WillFriend(userId, friendId) {
        const res = await FriendShip.findAll({
            attributes: ['userId', 'friendId', 'status'],
            where: {
                [Op.or]: [{ userId: friendId, friendId: userId }]
            }
        })
        return res
    }
    //(添加)关注好友
    async fetchFriend(userId, friendId) {
        try {
            const res = await FriendShip.create({
                userId, friendId
            })
            return res
        } catch (error) {
            console.log(error);
        }

    }

    //互关好友(同意)
    async becomeFriend(userId, friendId) {
        //userId为回关  friendId 为对面关注
        //有两种情况 status为0 或1 先查询是哪个数据  关注发送请求必然存在数据
        const realtion = await FriendShip.findAll({
            where: {
                friendId: userId,
                userId: friendId,
                status: 0
            }
        })
        const relationship = await FriendShip.findAll({
            where: {
                friendId,
                userId,
                status: 1
            }
        })
        if (realtion.length > 0) {
            const res = await FriendShip.update({ status: 2 }, {
                where: {
                    friendId: userId,
                    userId: friendId,
                    status: 0
                }
            })
            return res
        }
        //此时应该有对应状态 避免混乱 (建表字段错误)
        else if (relationship.length > 0) {
            const res = await FriendShip.update({ status: 2 }, {
                where: {
                    friendId,
                    userId,
                    status: 1
                }
            })
            return res
        }

    }

    //取消关注  ?分两种情况 此时状态应该为2   首先是关注人取消status改为1   二是被关注人取消status改为0
    async destroyFriend(userId, friendId) {
        //userid 取消关注方  friendid是对方
        //先查询状态? 是否为好友 //两种情况 好友 我已关关注  
        //先查询 状态看发起人与被发起人关系
        try {
            const relation = await FriendShip.findAll({
                attributes: ['userId', 'friendId', 'status'],
                where: {
                    [Op.or]: [{ userId, friendId, status: 2 }]
                }
            })//如果长度大于0 则为useid先关注  取消则变成1  否则则变为0

            if (relation.length > 0) {
                const res = await FriendShip.update({ status: 1 }, {
                    where: {
                        userId, friendId, status: 2
                    }
                })
                return { res, status: 1 }
            }

            const res = await FriendShip.update({ status: 0 }, {
                where: {
                    userId: friendId, friendId: userId, status: 2
                }
            })
            return { res, status: 1 }
        }
        catch (error) {
            console.log(error);
        }

    }

    //取消关注第二种情况 //单方面取消状态可为0 或 1 若取消后则 -1
    async breakrelation(userId, friendId) {
        //先查找记录 
        try {
            //查询是否存在关系
            const myfollowlist = await FriendShip.findAll({
                where: {
                    [Op.or]: [{ userId, friendId, status: 0 }]
                }
            })
            if (myfollowlist.length > 0) {
                //存在分析的步骤
                const res = await FriendShip.destroy({
                    where: {
                        [Op.or]: [{ userId, friendId, status: 0 }]
                    }
                })
                return res
            }

            //此为1的状态取消关注
            const myfanlist = await FriendShip.findAll({
                where: {
                    [Op.or]: [{ userId: friendId, friendId: userId, status: 1 }]
                }
            })
            //进行更新
            if (myfanlist.length > 0) {
                const res = await FriendShip.destroy({
                    where: {
                        [Op.or]: [{ userId: friendId, friendId: userId, status: 1 }]
                    }
                })
                return res
            }

        }
        catch (error) {
            console.log(error);
        }
    }

    //查询器关注我的
    async selectMyFriend(params) {
        const { userId, pageNo, pageSize } = params
        const limit = pageSize * 1
        const offset = (pageNo * 1 - 1) * pageSize
        const { count, rows } = await FriendShip.findAndCountAll({
            attributes: ['userId', 'status', 'friendId'],
            where: {
                [Op.or]: [{ FriendId: userId, status: 0 }, { userId, status: 1 }]
            },
            offset,
            limit
        })
        const Promiseresult = rows.map(item => {
            if (item.dataValues.status === 1) {
                const temp = item.dataValues.userId;
                item.dataValues.userId = item.dataValues.friendId;
                item.dataValues.friendId = temp;
            }
            // 如果 status 为 0，将其改为 1
            const modifiedStatus = item.dataValues.status === 0 ? 1 : item.dataValues.status;

            // 获取用户信息并合并数据
            return getUserInfo({ user_id: item.dataValues.userId }).then(({ user_nickname, image }) => {
                return Object.assign(
                    { userId: item.dataValues.userId, status: modifiedStatus },
                    { user_nickname, image }
                );
            });
        });
        // 查询user表字段? 关联失败 不作修改
        const result = await Promise.all(Promiseresult)

        return { result, count }
    }

    //查询我关注的
    async selectMyFollowFriend(params) {
        const { userId, pageNo, pageSize } = params
        const limit = pageSize * 1
        const offset = (pageNo * 1 - 1) * pageSize
        try {
            console.log(userId);

            const { count, rows } = await FriendShip.findAndCountAll({
                attributes: ['userId', 'status', 'friendId'],
                where: {
                    [Op.or]: [{ userId, status: 0 }, { userId, status: 2 }, { friendId: userId, status: 1 }, { friendId: userId, status: 2 }]
                },
                offset,
                limit
            })


            const Promiseresult = rows.map(item => {
                // 如果 status 为 0 或 1，则交换 userId 和 friendId
                if (
                    item.dataValues.status === 0 ||
                    item.dataValues.status === 1 ||
                    (item.dataValues.userId === userId && item.dataValues.status === 2)
                ) {
                    const temp = item.dataValues.userId;
                    item.dataValues.userId = item.dataValues.friendId;
                    item.dataValues.friendId = temp;
                }

                // 如果 status 是 1，则修改为 0
                item.dataValues.status = item.dataValues.status === 1 ? 0 : item.dataValues.status;

                // 获取用户信息
                return getUserInfo({ user_id: item.dataValues.userId }).then(({ user_nickname, image }) => {
                    return Object.assign(item.dataValues, { user_nickname, image });
                });
            });
            // 查询user表字段? 关联失败 不作修改
            const result = await Promise.all(Promiseresult)
            console.log(result);

            return { result, count }
        } catch (error) {
            console.log(error, 123);
        }

    }

    //查询我的朋友
    async MyFriends(params) {
        const { userId, pageNo, pageSize } = params;
        const limit = pageSize * 1;
        const offset = (pageNo * 1 - 1) * pageSize;

        try {
            const { count, rows } = await FriendShip.findAndCountAll({
                attributes: ['userId', 'status', 'friendId'],
                where: {
                    [Op.or]: [{ userId, status: 2 }, { friendId: userId, status: 2 }]
                },
                offset,
                limit
            });

            const Promiseresult = rows.map(item => {
                // 如果 userId 匹配并且 status 为 2，则交换 userId 和 friendId
                if (item.dataValues.status === 2 && item.dataValues.userId === userId) {
                    const temp = item.dataValues.userId;
                    item.dataValues.userId = item.dataValues.friendId;
                    item.dataValues.friendId = temp;
                }

                // 返回 getUserInfo 的 Promise
                return getUserInfo({ user_id: item.dataValues.userId }).then(({ user_nickname, image }) => {
                    return Object.assign(item.dataValues, { user_nickname, image });
                });
            });

            // 使用 Promise.all 处理所有异步操作
            const result = await Promise.all(Promiseresult);
            return { result, count };
        } catch (error) {
            console.log(error);
        }
    }

}

module.exports = new FriendService()